import { Component, OnInit, ViewChildren, QueryList } from '@angular/core'
import { FormBuilder, Validators, FormGroup } from '@angular/forms'
import { NzMessageService } from 'ng-zorro-antd'

import { ChargeStoreService } from '../charge-base.service'
import {
  makeAllControlDirty,
  getAAMSGroup,
  getAAMSMerchant,
  getAAMSStore,
  getAAMSAcquirer,
  acquirerEditPermission,
  agentEditPermission,
  storeEditPermission,
  merchantEditPermission,
} from 'app/utils/helpers'
import { IAamsItem, IAamsLevel } from '@shared/components/aams-select/aams-select.interface'
import { AamsSelectComponent } from '@shared/components/aams-select/aams-select.component'
import { SettingsService } from '@delon/theme'
import { User } from '@shared/interfaces/user'
import { I18NService } from '@core'
import { tap, take, map } from 'rxjs/operators'

@Component({
  selector: 'app-charge-new-system',
  templateUrl: './system.component.html',
})
export class TradeChargeNewSystemComponent implements OnInit {
  @ViewChildren(AamsSelectComponent) allAamsSelects: QueryList<AamsSelectComponent>

  validateForm: FormGroup

  chosenAcquirer: IAamsItem = {}
  chosenGroup: IAamsItem = {}
  chosenMerchant: IAamsItem = {}
  chosenStore: IAamsItem = {}

  form: FormGroup = this.fb.group({})

  constructor(
    public msg: NzMessageService,
    public fb: FormBuilder,
    public chargeStoreService: ChargeStoreService,
    public settings: SettingsService,
    private i18n: I18NService,
  ) {
    this.validateForm = this.fb.group({})
  }

  ngOnInit() {
    this.initValidateForm()
  }

  initValidateForm(): void {
    this.chargeStoreService.value$.pipe(
      map(addModel => addModel.systemInfo),
      tap(systemInfo => {
        this.form = this.fb.group({
          biz: [systemInfo, [Validators.required]]
        })
      }),
      take(1)
    ).subscribe()
  }

  checkValid(): boolean {
    if (!this.form.get('biz').value.intStoreCode) {
      const msg = this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('GENERAL.BIZ_LEVEL.STORE')})
      this.msg.error(msg)
      return false
    }

    this.pushDataToStore()
    this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    return true
  }

  pushDataToStore(): void {
    const data = this.form.get('biz').value
    this.chargeStoreService.setSystemValue(data)
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
